package com.gujiangbo.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/6/5 21:10
 * @Version: 1.0
 * @Description: 线程中断演示
 */
public class InterruptDemo {

    private static volatile Boolean isRunning = true;
    private static AtomicBoolean isRunningFlag = new AtomicBoolean(true);

    public static void main(String[] args) {
        // m1Volatile();
        //m2AtomicBoolean();
       // m3Interrupt();
    }

    private static void m3Interrupt() {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("t1 is stopped....");
                    break;
                }
                System.out.println("t1 is running ...");
            }


        }, "t1");
        t1.start();
        try{TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}
        Thread t2 = new Thread(t1::interrupt, "t2");
        t2.start();


    }

    private static void m2AtomicBoolean() {
        new Thread(() -> {
            while (isRunningFlag.get()) {
                System.out.println(Thread.currentThread().getName() + " is running.....");
                //暂停5秒钟线程
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + " is stopped....");
        }, "t1").start();
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            isRunningFlag.set(false);
        }, "t2").start();
    }

    private static void m1Volatile() {

        new Thread(() -> {
            while (isRunning) {
                System.out.println(Thread.currentThread().getName() + " is running....");
                //暂停5秒钟线程
                try {
                    TimeUnit.MILLISECONDS.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + " is stopped...");
        }, "a").start();

        //暂停5秒钟线程
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            isRunning = false;
        }, "b").start();

    }

}
